<template>
    <div class="wrapper" ref="wrapper">
        <div class="content">
            <slot></slot>
        </div>
    </div>
</template>

<script setup name="scroll">
    import { useDebounceFn } from '@vueuse/core';
    import MouseWheel from '@better-scroll/mouse-wheel';
    import ScrollBar from '@better-scroll/scroll-bar';
    import BScroll from 'better-scroll'
    import {ref,nextTick} from "vue"
    BScroll.use(MouseWheel)//鼠标滚轮
    BScroll.use(ScrollBar)//滚动条

    let scroll = ref(null)
    let wrapper = ref(null)
    let message = ref("hhh")
    const props = defineProps({
        probeType:{
            type: Number,
            default:2  // 1 2 3
        },
    })
    const emit = defineEmits(["scroll","pullingUp","upRefresh","pullingDown"])
    onMounted(()=>{
        // 初始化
        scroll.value = new BScroll(wrapper.value, {
            click: true,
            probeType: props.probeType,
            bounce:true,
            mouseWheel: true,//开启鼠标滚轮插件
            scrollbar: {
                fade: true,
                interactive: false // 1.8.0 新增
            },
            pullDownRefresh: {
                threshold: 50,
                stop: 20
            },
            // pullUpLoad: props.pullUpLoad
            pullUpLoad: {
                threshold: 50
            }
        })
        // 2.监听滚动的位置
        scroll.value.on('scroll', useDebounceFn((position) => {
            console.log(position);
            emit("scroll")
        }),500)

        // 3.监听上拉
        scroll.value.on('pullingUp',useDebounceFn(() => {
            console.log("pullingUp")
            emit("pullingUp")
        },500))
        // 4、下拉刷新
        scroll.value.on('pullingDown',useDebounceFn(() => {
            console.log("pullingDown")
            emit("pullingDown")
        },500))

        // 4、下拉刷新 这种也可以
        // scroll.value.on('touchEnd',useDebounceFn((pos) =>{  //上拉刷新
        //     if(pos.y > 30){
        //         console.log("上拉刷新");
        //         emit("upRefresh")
        //     }
        // }),500)
    })

    function scrollTo(x, y, time = 300) {
        scroll.value.scrollTo(x, y, time)
    }
    function finishPullUp() {
        // 在触发pullingUp之后必须 要手动调一下这个
        scroll.value.finishPullUp()
    }
    function finishPullDown() {
        // 在触发pullingDown之后必须 要手动调一下这个
        scroll.value.finishPullDown()
    }
    function refresh() {
        scroll.value.refresh();
    }

    //离开时y的滚动距离
    function getScrollY(){
        //有值返回无返回0
        return scroll.value.y ? scroll.value.y:0
    }


    onUnmounted(() => {
        // 移除BetterScroll
        scroll.value && scroll.value.destroy && scroll.value.destroy?.()
    })

    defineExpose({
        finishPullUp,
        finishPullDown
    })
</script>

<style scoped>
    .wrapper{
        height: 90vh;
        width: 100%;
        background-color: #99a9bf;
        overflow: hidden;
    }
    .content{
        min-height: 200vh;
    }
</style>